package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.sample.Card;

public class CardDaoImpl extends BaseDao{
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    /**
     * 显示列表
     */
    public List<Card> list(){
    List<Card> list=new ArrayList<>();
        try {
            conn=super.getConnection();
            String  sql="SELECT * FROM card";
            pstmt=conn.prepareStatement(sql);
            rs=pstmt.executeQuery();
            while (rs.next()) {
                Card card = new Card();
                card.setId(rs.getInt("id"));
                card.setUserName(rs.getString("userName"));
                card.setIdNumber(rs.getString("idNumber"));
                card.setStatus(rs.getInt("status"));
                card.setCreateDate(rs.getString("createDate"));
                list.add(card);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            super.closeAll(conn,pstmt,rs);
        }
        return  list;
    }

    /**
     * 办卡
     */
    public int addCard(Card card){
        int iRet=0;
        try {
            conn=super.getConnection();
            String  sql="INSERT INTO `card`( `userName`, `idNumber`,`status`, `createDate`) VALUES (?,?,1,?)";
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,card.getUserName());
            pstmt.setString(2,card.getIdNumber());
            pstmt.setString(3,card.getCreateDate());
            iRet=pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return iRet;
    }

    /**
     * 判断身份证是否存在
     */
    public int checkIdNUm(String date){
        int iRet=0;
        try {
            conn=getConnection();
            pstmt=conn.prepareStatement("select count(*) from card where idNumber=?");
            pstmt.setString(1,date);
            rs=pstmt.executeQuery();
            if (rs.next()) {
                iRet=rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return iRet;
    }

    /**
     * 禁用或启用
     */
    public int Status(int id,int status){
        int iRet=0;
        try {
            conn=super.getConnection();
            String  sql="UPDATE card SET `status` = ? WHERE `id` = ?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1,status);
            pstmt.setInt(2,id);
            iRet=pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return iRet;
    }
}
